package wrapper

import (
	"SQLWrapperForGO/common"
	"fmt"
	"strings"
)

/**
 * description：
 * <p>
 * </p>
 * change history:
 * date                      defect#    person       comments
 * -------------------------------------------------------------<p>
 * 2023/9/27 16:35          ********    kong.ruo    create file.
 *
 * @author kong.ruo
 * @date 2023/9/27 16:35
 *
 * @since go 1.20
 */

// OperationMode such as enum
type OperationMode struct {
	// mode : Eq , In , Not.....
	mode common.OperationMode
	// value : condition value
	value interface{}
}

// new Obj
func getNewMode(mode common.OperationMode, value interface{}) *OperationMode {
	return &OperationMode{
		mode:  mode,
		value: value,
	}
}

// buildCondition get condition sql
func buildCondition(qc map[string]*OperationMode) string {
	cond := make([]string, 0)
	for column, value := range qc {
		cond = append(cond, fmt.Sprintf("%s%s", column, buildMode(value)))
	}
	return joinConditions(cond, "AND")
}

// buildMode from Mode build sql
func buildMode(value *OperationMode) string {
	mode := value.mode
	va := value.value
	switch mode {
	case common.Eq:
		return fmt.Sprintf(" = %v", TypeCheck(va))
	case common.In:
		vas, ok := va.([]string)
		if ok {
			return fmt.Sprintf(" in ( '%s' )", strings.Join(vas, "' , '"))
		}
		vai, ok := va.([]int)
		if ok {
			return fmt.Sprintf(" in (%s)", strings.Join(S2I(vai), " , "))
		}
		return ""
	default:
		// 默认为 eq
		return fmt.Sprintf(" = %v", TypeCheck(va))
	}
}

func joinConditions(conditions []string, separator string) string {
	if len(conditions) == 0 {
		return ""
	}

	if len(conditions) == 1 {
		return conditions[0]
	}
	return strings.Join(conditions, separator)
}
